package com.softsec.isc.apkextract;

import java.util.ArrayList;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import brut.androlib.AndrolibException;
import brut.androlib.res.AndrolibResources;
import brut.androlib.res.data.ResPackage;
import brut.androlib.res.data.ResResource;
import brut.androlib.res.data.ResTable;
import brut.androlib.res.data.ResValuesFile;
import brut.androlib.res.data.value.ResScalarValue;
import brut.androlib.res.decoder.ARSCDecoder;
import brut.androlib.res.decoder.AXmlResourceParser;
import brut.androlib.res.decoder.ResAttrDecoder;
import brut.androlib.res.decoder.ResFileDecoder;
import brut.androlib.res.util.ExtFile;
import brut.directory.DirectoryException;
import brut.util.Duo;

public class ResExtrator {
	
	static Logger logger = LogManager.getLogger(ResExtrator.class);
	
	private String packageNameString = "";
	private List<String> resValueStrings = new ArrayList<String>();
	
	public String getPackageNameString() {
		return packageNameString;
	}
	public List<String> getResValueStrings() {
		return resValueStrings;
	}
	
	public void getPackageAndResvalue(String filePath) {
		//package name...
		ResTable resTable = new ResTable();
		try {
//			logger.info("START...");
//			TODO Edit by lcz
//			edit the source code of Apktool-lib,brut.androlib.res.decoder.ARSCDecoder...
//			Then edit back....
//			ARSCDecoder decoder = new ARSCDecoder(new ExtFile(filePath).getDirectory().getFileInput("resources.arsc"), resTable, false, false);
//			ResPackage[] resPackages = decoder.readTable();
			ResPackage[] resPackages = ARSCDecoder.decode(new ExtFile(filePath).getDirectory().getFileInput("resources.arsc"), false, false, resTable).getPackages();
			resTable.addPackage(resPackages[0], true);
			packageNameString = resPackages[0].getName();
//			logger.info(packageNameString);
		} catch (AndrolibException | DirectoryException e) {
			e.printStackTrace();
		}
		
		AndrolibResources ar = new AndrolibResources();
		Duo<ResFileDecoder, AXmlResourceParser> duo = ar.getResFileDecoder();
		ResAttrDecoder attrDecoder = duo.m2.getAttrDecoder();
		attrDecoder.setCurrentPackage(resTable.listMainPackages().iterator().next());
		for (ResPackage pkg : resTable.listMainPackages()) {
			attrDecoder.setCurrentPackage(pkg);
			for (ResValuesFile valuesFile : pkg.listValuesFiles()) {
				for (ResResource res : valuesFile.listResources()) {
					if (valuesFile.isSynthesized(res)) {
						continue;
					}
					String type = res.getResSpec().getType().getName();
					if ("string".equals(type)) {
						ResScalarValue rv = (ResScalarValue) res.getValue();
						//"app_name".equal(res.getResSpec().getName());
						try {
							String resValueString = rv.encodeAsResXmlItemValue();
							resValueStrings.add(resValueString);
//							logger.info(resValueString);
						} catch (AndrolibException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
	}
}
